package com.bfxy.rabbit.producer.service;

import com.bfxy.rabbit.producer.constant.BrokerMessageStatus;
import com.bfxy.rabbit.producer.entity.BrokerMessage;
import com.bfxy.rabbit.producer.mapper.BrokerMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @describte: 存储Message
 * @program:foodie-dev
 * @author:zhengdp
 * @create:2021-09-15 22:20:11
 **/
@Service
public class MessageStoreService {

    @Autowired
    private BrokerMessageMapper brokerMessageMapper;

    // 将Message副本先入库
    public int insert(BrokerMessage brokerMessage){
        return this.brokerMessageMapper.insert(brokerMessage);
    }

    // 更新消息发送日志状态为SEND_OK
    public void success(String messageId){
        this.brokerMessageMapper.changeBrokerMessageStatus(messageId,
                BrokerMessageStatus.SEND_OK.getCode(),
                new Date());
    }

    // 更新消息发送日志状态为SEND_FAIL
    public void failure(String messageId){
        this.brokerMessageMapper.changeBrokerMessageStatus(messageId,
                BrokerMessageStatus.SEND_FAIL.getCode(),
                new Date());
    }

    // 更新 Message日志的状态，但我感觉nexttry也需要进行更新
    public List<BrokerMessage> fetchTimeOutMeesage4Retry(BrokerMessageStatus brokerStatus){
        return this.brokerMessageMapper.queryBrokerMessageStatus4Timeout(brokerStatus.getCode());
    }

    // 查询 Message 是否在数据库中存在
    public BrokerMessage query(String messageId){
        return this.brokerMessageMapper.selectByPrimaryKey(messageId);
    }

    /*
    更新 重试次数和修改时间
     */
    public int updateTryCount(String brokerMessageId) {
        return this.brokerMessageMapper.update4TryCount(brokerMessageId, new Date());
    }


}
